package com.wash.shoes.controller.pc;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.FulFillEnum;
import com.wash.shoes.common.enums.JdEnum;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.common.utils.ResultUtil;
import com.wash.shoes.domain.dto.JdLogisticsTrack;
import com.wash.shoes.domain.dy.request.DyRefundRequest;
import com.wash.shoes.domain.dy.request.DyServiceUpdateRequest;
import com.wash.shoes.domain.mtbusy.MtUpdateFulFillInfo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import com.wash.shoes.util.AliYunSmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author ljg
 * @since 2024-09-16
 */
@Api(tags = {"PC-jd的回调"})
@RestController
@RequestMapping("/jdCallBack")
@Slf4j(topic = "jd-record")
public class JdCallBackController {

    @Resource
    OrderService orderService;

    @Resource
    HttpServletRequest httpServletRequest;

    @Autowired
    MtUpdateFulFillInfo mtUpdateFulFillInfo;

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    DyServiceUpdateRequest serviceUpdateRequest;

    @Autowired
    private DyRefundRequest dyRefundRequest;

    @ApiOperation("jd物流轨迹订阅消息回调")
    @PostMapping(value = "jdTrackingPush")
    R<String> jdCallBack5810001(@RequestBody String logisticsTrack) {
        try {
            if (StringUtils.isEmpty(logisticsTrack)) {
                log.error("jd的物流轨迹订阅回调消息为空 {}", logisticsTrack);
                return ResultUtil.createErrorR("物流轨迹消息为空");
            }
            log.info("jd的物流轨迹订阅回调消息 {}", logisticsTrack);
            JdLogisticsTrack logisticsTrackObject = JSONObject.parseObject(logisticsTrack, JdLogisticsTrack.class);
            log.info("jd的物流轨迹订阅回调消息转换 {}", logisticsTrackObject.toString());


            //通过物流订单查询订单是否存在
            OrderPo orderPo = orderService.getByJdWayBillCode(logisticsTrackObject.getWaybillCode());

            if (Objects.isNull(orderPo)) {
                log.error("通过物流单号查询订单为空 {}", logisticsTrack);
                return ResultUtil.createErrorR("通过物流单号查询订单为空");
            }
            log.info("jd回调订单信息为 {}", orderPo.toString());

            //物流状态为妥投，就说明鞋子已经到店签收，更新订单状态为待入库
            if (StringUtils.equals(orderPo.getType(), "取鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_TOU_T.getStatus()) {
                // 如果今天的订单没有入库，就更新状态，入库了到状态3了，就不更新状态
                if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PICK_UP_SHOES.getStatus())) {
                    //更新订单状态待入库
                    orderPo.setStatus(OrderStatusEnum.PENDING_STORAGE.getStatus());
                    orderService.updateById(orderPo);
                    log.info("更新美团的物流信息为 [衣物已送达]");
                    mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.ARRIVED, logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone());
                }
            }
            //如果是送鞋中，且物流状态为妥投也把订单更新为完成
            if (StringUtils.equals(orderPo.getType(), "送鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_TOU_T.getStatus()) {
                //更新订单状态为已完成
                orderPo.setStatus(OrderStatusEnum.COMPLETED.getStatus());
                // 更新都应的订单为服务完成
                serviceUpdateRequest.updateFullFill(orderPo, 4);
                orderService.updateById(orderPo);
                log.info("更新美团的物流信息为 [履约完成(通用)]");
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.COMPLETION, logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone());
            }

            // 390 已下发
            if (StringUtils.equals(orderPo.getType(), "取鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_YI_XF.getStatus()) {
                // 更新美团的信息的状态
                log.info("更新美团的物流信息为 [上门取衣服中]");
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.ALLOCATED, logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone());
                AliYunSmsUtil.receiveShoeSms(logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone(), orderPo.getCustomPhone());
            }

            if (StringUtils.equals(orderPo.getType(), "送鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_YI_XF.getStatus()) {
                // 更新美团的信息的状态
                log.info("更新美团的物流信息为 [返回中(洗衣)]");
                mtUpdateFulFillInfo.fulfillInfo(orderPo.getId(), FulFillEnum.RETURNING, logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone());
            }

            //鞋子返回给用户派送中发送短信
            if (StringUtils.equals(orderPo.getType(), "送鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_PAI_SZ.getStatus()) {
                log.info("送鞋派送中,发送短信通知用户!!!!");
                AliYunSmsUtil.sendShoeSms(logisticsTrackObject.getOperatorName(), logisticsTrackObject.getOperatorPhone(), orderPo.getCustomPhone());
            }

            // 如果送鞋为取消，就需要修改定单的状态为，带出库
            if (StringUtils.equals(orderPo.getType(), "送鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_YI_QX.getStatus()) {
                // 京东送鞋取消，更新订单的信息为待出库
                log.info("京东送鞋取消，更新订单的信息为待出库，可以重新出库");
                orderPo.setStatus(OrderStatusEnum.PENDING_OUTBOUND.getStatus());
                orderService.updateById(orderPo);
            }
            // 如果订单状态为取鞋中，且物流状态取消，就修改订单状态为取消
            if (Objects.equals(OrderStatusEnum.PICK_UP_SHOES.getStatus(), orderPo.getStatus()) && StringUtils.equals(orderPo.getType(), "取鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_YI_QX.getStatus()) {
                // 京东送鞋取消，更新订单的信息为待出库
                log.info("京东取鞋取消，更新订单的信息为已取消订单NO为:" + orderPo.getOrderNo());
                orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
                orderService.updateById(orderPo);
                //如果是抖音的订单，就调用抖音的取消接口
                if ("3".equals(orderPo.getComeFrom())) {

                    //检查是否退款
                    String refundStatus = dyRefundRequest.queryRefund(orderPo);
                    if (!"SUCCESS".equals(refundStatus)) {
                        try {
                            dyRefundRequest.refund(orderPo);
                        } catch (Exception e) {
                            log.error("抖音取鞋物流取消,发起抖音退款失败:orderid:" + orderPo.getId(), e);
                        }
                    }
                }
            }

            // 420 已揽收 小程序处理已经揽收的状态
            if (StringUtils.equals(orderPo.getType(), "取鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_YI_LS.getStatus()) {
                // 更新美团的信息的状态
                log.info("更新小程序的订单状态为 [送洗中]");
                orderPo.setXcxStatus(2);
                orderService.updateById(orderPo);
                // 如果是抖音的订单,就改变抖音的订单状态为 1- 已寄出（已取件）已经揽收以后不能取消.
                serviceUpdateRequest.updateFullFill(orderPo, 1);
            }

            // 440 派送中 小程序处理 派送中
            if (StringUtils.equals(orderPo.getType(), "送鞋") && logisticsTrackObject.getCategory() == JdEnum.ORDER_PAI_SZ.getStatus()) {
                // 更新美团的信息的状态
                log.info("更新小程序的订单状态为 [返回中(派送中)]");
                orderPo.setXcxStatus(5);
                orderService.updateById(orderPo);
            }

            // 更新物流的状态
            OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(logisticsTrackObject.getWaybillCode());
            if (orderTransportPo != null) {
                orderTransportPo.setStatus(String.valueOf(logisticsTrackObject.getCategory()));
                orderTransportService.updateById(orderTransportPo);
            }
            log.info("==============================");
            log.info("==============================");
            return ResultUtil.createSucR();
        } catch (Exception e) {
            log.error("jd的物流轨迹订阅回调异常 {}", e);
            return ResultUtil.createErrorR("jd的物流轨迹订阅回调异常");
        }

    }
}

